<template>
  <div class="page-container">
    <!-- 用户登录状态 - 仅在未登录时显示 -->
    <!-- <div class="user-auth-status" v-if="!isLoggedIn">
      <div class="login-prompt">请连接钱包并登录以使用完整功能</div>
      <van-button type="primary" @click="handleLogin">连接钱包登录</van-button>
    </div> -->
    <!-- 特色产品展示 -->
    <FeaturedProduct 
      :product="featuredProduct" 
      @click="navigateTo(`/product/${featuredProduct.id}`)" 
    />

    <!-- 分红池卡片 -->
    <DividendPool
      :amount="dividendPoolInfo.totalAmount"
      :estimate="dividendPoolInfo.estimatedDividend"
      :yesterdayDividend="dividendPoolInfo.yesterdayDividend"
      :currency="dividendPoolInfo.currency"
      @click="goToParticipation"
    />

    <!-- 热销商品区域 -->
    <div class="card mt-16">
      <div class="section-header">
        <h3 class="section-title">热销商品</h3>
        <div class="view-all" @click="navigateTo('/products')">
          查看全部 <van-icon name="arrow" />
        </div>
      </div>
      
      <div class="grid-2">
        <ProductCard 
          v-for="product in hotProducts" 
          :key="product.id"
          :product="product"
          @click="navigateTo(`/product/${product.id}`)"
        />
      </div>
    </div>

    <!-- 成熟项目区域 -->
    <div class="card mt-16">
      <div class="section-header">
        <h3 class="section-title">成熟项目</h3>
      </div>
      
      <div class="projects-list">
        <ProjectCard 
          v-for="project in projects" 
          :key="project.id"
          :project="enhancedProject(project)"
          @click="goToProjectDetail(project.id)"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showLoadingToast, closeToast } from 'vant'
import FeaturedProduct from '@/components/FeaturedProduct.vue'
import DividendPool from '@/components/DividendPool.vue'
import ProductCard from '@/components/ProductCard.vue'
import ProjectCard from '@/components/ProjectCard.vue'
import { goods, dividend, project } from '@/api'

const router = useRouter()

// 商品数据
const featuredProduct = ref({})
const hotProducts = ref([])
const loading = ref(false)

// 分红池数据
const dividendPoolInfo = ref({
  totalAmount: '0',
  estimatedDividend: '0',
  yesterdayDividend: '0',
  participantsCount: 0,
  currency: 'USDT'
})

// 获取商品数据
const fetchGoodsData = async () => {
  loading.value = true
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  })
  
  try {
    // 获取商品列表，热销商品参数hot=1
    const response = await goods.getGoodsList({
      page: 1,
      size: 5,
      hot: '1',
      count: false
    })
    
    // 检查响应数据结构
    const goodsData = response.data.list || response
    
    if (goodsData && Array.isArray(goodsData) && goodsData.length > 0) {
      // 第一个商品作为特色商品
      featuredProduct.value = transformGoodsData(goodsData[0])
      
      // 剩余商品作为热销商品
      hotProducts.value = goodsData.slice(1, 5).map(transformGoodsData)
    }
  } catch (error) {
    console.error('获取商品数据失败:', error)
    showToast('获取商品数据失败，显示默认数据')
  } finally {
    loading.value = false
    closeToast()
  }
}

// 转换商品数据格式
const transformGoodsData = (item) => {
  // 获取第一个规格的价格，如果没有规格则为0
  const price = item.specs && item.specs.length > 0 
    ? item.specs[0].usdtPrice 
    : '0.00'
  
  // 获取第一张图片，如果有多张图片用逗号分隔
  const imageUrl = item.images 
    ? item.images.split(',')[0] 
    : 'https://images.unsplash.com/photo-1523275335684-37898b6baf30?q=80&w=1000&auto=format&fit=crop'
  
  return {
    id: item.id.toString(),
    name: item.productName,
    price: price,
    image: imageUrl,
    description: item.detail || '',
    goodsNo: item.goodsNo,
    specs: item.specs || []
  }
}




// 项目数据
const projects = ref([])

// 获取项目数据
const fetchProjectData = async () => {
  try {
    const response = await project.getProjectList({
      page: 1,
      size: 3,
      status: 'active'
    })
    
    // 检查响应数据结构
    const projectData = response.data.list || response
    
    if (projectData && Array.isArray(projectData) && projectData.length > 0) {
      projects.value = projectData
    } else {
      // 如果没有数据，设置默认数据
      setDefaultProjects()
    }
  } catch (error) {
    console.error('获取项目数据失败:', error)
    showToast('获取项目数据失败，显示默认数据')
  }
}

// 为项目添加额外属性（如果API返回的数据缺少某些属性）
const enhancedProject = (project) => {
  // 如果项目已经包含所有需要的属性，直接返回
  if (project.image && project.earnings && project.currency) {
    return project
  }
  
  // 否则添加缺失的属性
  return {
    ...project,
    image: project.image || (project.id === '1' 
      ? 'https://images.unsplash.com/photo-1523275335684-37898b6baf30?q=80&w=1000&auto=format&fit=crop'
      : 'https://images.unsplash.com/photo-1546868871-7041f2a55e12?q=80&w=1000&auto=format&fit=crop'),
    earnings: project.earnings || (project.id === '1' ? '150.00' : '45.00'),
    currency: project.currency || 'HDFS'
  }
}

// 导航方法
const goToParticipation = () => {
  router.push('/pool-join')
}

const goToProjectDetail = (projectId) => {
  router.push(`/project/${projectId}`)
}

const navigateTo = (path) => {
  if (path.startsWith('/product/')) {
    router.push(path)
  } else if (path === '/products') {
    router.push('/products')
  } else {
    router.push(path)
  }
}


// 获取分红池数据
const fetchDividendPoolData = async () => {
  try {
    const response = await dividend.getDividendPoolInfo();
    if (response && response.data) {
      dividendPoolInfo.value = response.data;
    }
  } catch (error) {
    console.error('获取分红池数据失败:', error);
  }
};

// 在页面加载时自动检查钱包连接状态并获取数据
onMounted(async () => {  
  // 获取商品数据
  fetchGoodsData();
  
  // 获取分红池数据
  fetchDividendPoolData();
  
  // 获取项目数据
  fetchProjectData();

  // 尝试连接钱包
  //await web3Interceptor.checkWalletConnection();
});
</script>

<style scoped>
.page-container {
  padding-bottom: 24px;
}

.projects-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 用户登录状态样式 */
.user-auth-status {
  background-color: white;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  border: 2px solid #f0f0f0;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.user-nickname {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.user-address {
  font-size: 12px;
  color: #666;
  font-family: monospace;
}

.login-prompt {
  font-size: 14px;
  color: #666;
  margin-right: 12px;
}
</style>
